package com.itcam.daijia.customer.controller;

import ch.qos.logback.classic.spi.EventArgUtil;
import com.itcam.daijia.common.constant.RedisConstant;
import com.itcam.daijia.common.login.NGLogin;
import com.itcam.daijia.common.result.Result;
import com.itcam.daijia.common.util.AuthContextHolder;
import com.itcam.daijia.customer.service.CustomerService;
import com.itcam.daijia.customer.service.OrderService;
import com.itcam.daijia.model.form.customer.ExpectOrderForm;
import com.itcam.daijia.model.form.customer.UpdateWxPhoneForm;
import com.itcam.daijia.model.vo.customer.CustomerLoginVo;
import com.itcam.daijia.model.vo.customer.ExpectOrderVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

@Slf4j
@Tag(name = "客户API接口管理")
@RestController
@RequestMapping("/customer")
@SuppressWarnings({"unchecked", "rawtypes"})
public class CustomerController {

    @Autowired
    private CustomerService customerService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OrderService orderService;

    /**
     * 小程序授权登录
     * @param code
     * @return
     */
    @Operation(summary = "小程序授权登录")
    @GetMapping("/login/{code}")
    public Result<String> wxLogin(@PathVariable String code) {
        return Result.ok(customerService.login(code));
    }

    /**
     * 根据token获取用户信息
     *
     * @param token 用户登录凭证
     * @return 返回用户信息
     */
    @Operation(summary = "根据token获取用户信息")
    @GetMapping("/getCustomerLoginInfo")
    @NGLogin
    public Result<CustomerLoginVo> getCustomerLoginInfo(@RequestHeader("token") String token) {
        // 从 Redis 中根据 token 获取用户 ID
        String customerId = (String) redisTemplate.opsForValue().get(RedisConstant.USER_LOGIN_KEY_PREFIX + token);
        // 返回用户信息
        return Result.ok(customerService.getCustomerLoginInfo(Long.parseLong(customerId)));
    }


    /**
     * 更新用户微信手机号
     *
     * @param updateWxPhoneForm 包含用户ID和微信登录凭证的表单
     * @return 返回更新是否成功的布尔值
     */
    @Operation(summary = "更新用户微信手机号")
    @NGLogin
    @PostMapping("/updateWxPhone")
    public Result updateWxPhone(@RequestBody UpdateWxPhoneForm updateWxPhoneForm) {
        // 设置表单中的用户ID为当前登录用户的ID
        updateWxPhoneForm.setCustomerId(AuthContextHolder.getUserId());
        // 调用服务层方法更新微信手机号码
        return Result.ok(customerService.updateWxPhoneNumber(updateWxPhoneForm));
    }

    /**
     * 预估订单数据
     * @param expectOrderForm
     * @return
     */
    @Operation(summary = "预估订单数据")
    @NGLogin
    @PostMapping("/expectOrder")
    public Result<ExpectOrderVo> expectOrder(@RequestBody ExpectOrderForm expectOrderForm) {
        return Result.ok(orderService.expectOrder(expectOrderForm));
    }

}

